package com.leyou.user.service;

import com.leyou.common.constants.MQConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;  //spring的加密

    private static String SMS_CODE_PRE = "SMS:CODE:PRE:";

    //验证手机号或者用户名
    public Boolean checkUsernameAndPhone(String data, Integer type) {
        User user = new User();
        if (data == null) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        switch (type) {
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        int count = userMapper.selectCount(user);
        return !(count > 0);
    }

    //发送短信
    public void sendCheckCode(String phone) {
        //先生成验证码
        String code = RandomStringUtils.randomNumeric(6);
        //String code = "123456";
        //自己存入redis中
        redisTemplate.opsForValue().set(SMS_CODE_PRE + phone, code,2, TimeUnit.HOURS);
        //封装发短信的内容
        Map<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        //向mq中发送一份
        amqpTemplate.convertAndSend(MQConstants.Exchange.SMS_EXCHANGE_NAME, MQConstants.RoutingKey.VERIFY_CODE_KEY, msg);
    }

    public void register(User user, String code) {
        //获取redis中的code
        String redieCode = redisTemplate.opsForValue().get(SMS_CODE_PRE + user.getPhone());
        //查看用户填写的验证码是否正确
        if (!redieCode.equals(code)) {
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }
        //对密码进行加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //保存用户信息
        int count = userMapper.insertSelective(user);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    public UserDTO findUserInfo(String username, String password) {
        try {
            User user = new User();
            user.setUsername(username);
            User record = userMapper.selectOne(user);
            if (passwordEncoder.matches(password, record.getPassword())) {
                return BeanHelper.copyProperties(record, UserDTO.class);
            }
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

    }
}
